<?php
namespace app\common\controller;

use think\Request;
use think\Db;
use app\common\adapter\AuthAdapter;
use app\common\controller\Common;


/**
 * this interface aim to simplify the user's authentic verification
 *
 * more information, see ApiPublic
 *
 */
class ApiCommon extends Common
{
	public function initialize()
	{
		parent::initialize();
		$authKey = $this->request->header('authkey');
		$cache = cache('Auth_'.$authKey);

		// 校验authKey
		if (strlen($authKey)<=32) {
			header('Content-Type:application/json; charset=utf-8');
			exit(json_encode(['code'=>STATUS_RE_AUTH, 'errmsg'=>'需要登陆'.$authKey.'='.strlen($authKey)]));
		}

		if (empty($cache)){
			$userModel=new \app\admin\model\AdminUser;
			if ($userModel->createUserCache($authKey)){
				$cache = cache('Auth_'.$authKey);
			} else {
				header('Content-Type:application/json; charset=utf-8');
				exit(json_encode(['code'=>STATUS_RE_AUTH, 'errmsg'=>'登录失效或账号已被禁用']));
			}
		}

		$request = $this->request;
		$UserInfo=$cache['UserInfo'];
		if (!in_array(0,$UserInfo['gids'],true)){
			//if not the super administrator,exec checking process.
			$ruleName = $request->module().'.'.$request->controller().'.'.$request->action();
			if (!\app\common\adapter\AuthAdapter::checkRule(strtolower($ruleName), $UserInfo)) {
				header('Content-Type:application/json; charset=utf-8');
				exit(json_encode(['code'=>STATUS_AUTH_FAIL,'errmsg'=>'没有执行权限']));
			}
		}
		$GLOBALS['userInfo'] = $UserInfo;
	}


}
